// 查询订单列表
const cloud = require('wx-server-sdk');
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});
const db = cloud.database();
const dbCmd = db.command;
exports.main = async (event, context) => {
  const pageNum = event.pageNum || 1;
  const pageSize = event.pageSize || 10;
  if (!event.openId) {
    return {
      msg: "缺少openId",
      code: 500
    }
  }
  const successObj = {
    '1': dbCmd.lte('1'),
    "2": "1",
    "3": "0"
  }
  const lastCreateTime = event.lastCreateTime || event.inTime;
  // 获取总数
  const {
    total
  } = await db.collection("userOrders").count();
  // 计算一共多少页
  const total_times = Math.ceil(total / pageSize);
  const res = await db.collection('userOrders')
  // .aggregate()
    .orderBy("success", "asc")
    // .orderBy("endTime","desc")
    .orderBy("createTime", event.sortCreateTime||"desc")
    .where(dbCmd.and([{
        openId: event.openId
      },
      {
        success: successObj[event.success]
      }
    ]))
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .get();
  return {
    ...res,
    total: total, //总数
    totalPage: total_times, //总页数
    code: 200
  }
}